﻿package 
{
	import flash.events.AsyncErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	import flash.net.SharedObject;
	

	
	/**
	 * 
	 * @author chery
	 */
	public class Debug
	{
		private static var instance:Debug;//单例
		private static var _connName:String;//连接名称
		private var lc:LocalConnection;//本地连接
		
		/**
		 * 
		 * @throws Error
		 */
		public function Debug()
		{
			if (instance != null) throw Error("调试类只能用Debug.getInstance()来获取实例.");
			instance = this;
			initializeDebug();	
		}
		/**
		 * 单例
		 */		
		public static function getInstance():Debug
		{
			if (instance == null) instance = new Debug();
			return instance;
		}
		/**
		 * 设连接名称
		 */		
		public static function set connName(s:String):void
		{
			_connName = s;
		}
		/**
		 * 取连接名称
		 */		
		public static function get connName():String
		{
			return _connName;
		}
		/**
		 * 显示对象信息
		 * @param Obj:Object
		 * */
		public static function disObj(Obj:Object):void{
			for(var i:* in Obj){
				trace(i,Obj[i])
			}
		}
		/**
		 * 输出调试
		 * Debug.getInstance()._trace(...arguments); 
		 */		
		public function _trace(...arguments):void
		{
			var str:String = "";
			for(var i:uint = 0; i < arguments.length; i++)
			{
				if(arguments[i] === null)
				arguments[i] = "null";
				if(arguments[i] === undefined)
				arguments[i] = "undefined";
				if(str == "")
				{
					str = arguments[i].toString();
				} else {
					str = str + " "  + arguments[i].toString();
				}
			}
			try {
				lc.send(_connName,"debugTrace",str);
			} catch(error:Error) {
				//trace(">>> LocalConnection发送错误");
			}
			trace(str);
		}
		/**
		 * 构造函数初始化
		 */		
		private function initializeDebug():void
		{
			if(!_connName) throw Error("调试类Debug.connName需先赋值.");
			lc = new LocalConnection();
			lc.addEventListener(AsyncErrorEvent.ASYNC_ERROR,lcAsyncError);
			lc.addEventListener(SecurityErrorEvent.SECURITY_ERROR,lcSecurityError);
			lc.addEventListener(StatusEvent.STATUS,lcStatus);
		}
		/**
		 * LocalConnection异步错误
		 */		
		private function lcAsyncError(event:AsyncErrorEvent):void
		{
			//trace(">>> LocalConnection异步错误 error: " + event.error);
		}
		/**
		 * LocalConnection安全错误
		 */		
		private function lcSecurityError(event:SecurityErrorEvent):void
		{
			//trace(">>> LocalConnection安全错误 text: " + event.text);
		}
		/**
		 * LocalConnection状态
		 */		
		private function lcStatus(event:StatusEvent):void
		{
			//trace(">>> LocalConnection状态 level: " + event.level + " code: " + event.code);
		}
	}
}